98. 验证二叉搜索树
为保证权益,题目请参考 98. 验证二叉搜索树(From LeetCode).
解决方案1
CPP
C++
/*
* LeetCode 98. 验证二叉搜索树
* Author: Keven Ge
* Date: 2020-04-05
*/
#include <iostream>
#include <limits.h>
using namespace std;
// Definition for a binary tree node.
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
class Solution {
public:
bool isValidBST(TreeNode *root) {
return dfs(root, LONG_MIN, LONG_MAX);
}
bool dfs(TreeNode *root, long min_limit, long max_limit) {
if (root) {
if (root->val > min_limit && root->val < max_limit) {
if(dfs(root->left, min_limit, root->val) && dfs(root->right, root->val, max_limit)){
return true;
}
}
return false;
}
return true;
}
};
int main() {
return 0;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43